class Api::V1::BetsController < Api::V1::BaseController
  def index
    @bets = @current_user.bets.order("created_at DESC").page(params[:page]).per(params[:per])
  end

  def create
    @bet = @current_user.bets.build bet_params
    @bet.state = :pending
    @game = Game.find @bet.game_id
    if @game.blank?
      render json: { result: false, message: '该比赛不存在.' }, status: :ok and return
    end
    if @bet.master_or_guest != @game.master_or_guest
      render json: { result: false, message: '不能投注该队.' }, status: :ok and return
    end
    if @bet.save
      @plan = Plan.where(
        user_id: @current_user.id,
        team_id: @bet.team_id,
        state: :pending,
        propose: @game.propose
      ).first
      if @plan.blank?
        @plan = Plan.create(
          user_id: @current_user.id,
          team_id: @bet.team_id,
          state: :pending,
          propose: @game.propose,
          name: @game.remark
        )
      end
      @bet.update(plan_id: @plan.id)
      if not @game.pending?
        if @game.winned?
          if @bet.master_or_guest
            @bet.update(state: :win, total_fee: @bet.money * @game.master_index)
          else
            @bet.update(state: :win, total_fee: @bet.money * @game.guest_index)
          end
          @bet.plan.update(state: :completed)
        elsif @game.losed?
          @bet.update(state: :lose, total_fee: @bet.money)
        elsif @game.winned_half?
          if @bet.master_or_guest
            @bet.update(state: :winned_half, total_fee: @bet.money * @game.master_index * 0.5)
          else
            @bet.update(state: :winned_half, total_fee: @bet.money * @game.guest_index * 0.5)
          end
          @bet.plan.update(state: :completed)
        elsif @game.losed_half?
          if @bet.master_or_guest
            @bet.update(state: :losed_half, total_fee: @bet.money * 0.5)
          else
            @bet.update(state: :losed_half, total_fee: @bet.money * 0.5)
          end
        elsif @game.tie?
          @bet.update(state: :tie, total_fee: 0)
        end
      end
      render json: { result: true, message: '计划成功.' }, status: :ok
    else
      render json: { result: false, message: '计划出错.' }, status: :ok
    end
  end

  private

  def bet_params
    params.require(:bet).permit(:game_id, :team_id, :master_or_guest, :money)
  end
  
end
